#!/usr/bin/python
#-*-coding:utf-8-*-

import wx.aui,os.path
import lib
from lib.pageModule import *


try:
    dirName = os.path.dirname(os.path.abspath(__file__))
except NameError:  # We are the main py2exe script, not a module
    import sys
    dirName = os.path.dirname(os.path.abspath(sys.argv[0]))
bitmapDir = os.path.join(dirName, 'img\\bitmaps')

class TaskBarIcon(wx.TaskBarIcon):
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        self.frame = frame
        self.HasEvent = 0
        self.Blink = 0
        self.PageJump = 3
        self.SetIcon(wx.Icon(name='img/icon/favicon.ico', type=wx.BITMAP_TYPE_ICO), u'自动化测试平台!')
        self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.OnTaskBarClick)

    def OnTaskBarClick(self, event):
        self.HasEvent = 0
        self.SetIcon(wx.Icon(name='img/icon/favicon.ico', type=wx.BITMAP_TYPE_ICO), u'自动化测试平台!')
        if self.frame.IsIconized():
           self.frame.Iconize(False)
        if not self.frame.IsShown():
           self.frame.Show(True)
        self.frame.Raise()

class wxClient(wx.Frame):
    def __init__(self,screen_width,screen_height):
        self.client_width = screen_width
        self.client_height = screen_height - 40
        wx.Frame.__init__(self, None, -1, u"Python测试工具", style=wx.DEFAULT_FRAME_STYLE, size=(self.client_width, self.client_height))
        self.cpu = {}
        self.cpu["frame"] = self
        self.cpu["data"] = lib.DataCenter()
        self.cpu["pager"] = None
        self.cpu["panel"] = {}

        self.cpu["data"].client_width = self.client_width
        self.cpu["data"].client_height = self.client_height
        self.cpu["data"].contentPanel_width = (self.client_width - self.cpu["data"].menuPanel_width)/2
        self.cpu["data"].contentPanel_height = self.client_height
        self.cpu["data"].logPanel_width = (self.client_width - self.cpu["data"].menuPanel_width)/2
        self.cpu["data"].logPanel_height = self.client_height

        self.toolPanel_width = self.cpu["data"].toolPanel_width
        self.contentPanel_width = self.cpu["data"].contentPanel_width
        self.logPanel_width = self.cpu["data"].logPanel_width

        self.init_menu = False
        self.init_page = False
        self.init_tool = False
        self.menu_projectName = ''
        self.pyToolName = ''
        self.pager = None

        self.cpu["font"]         = {}
        self.cpu["font"]["16_b"] = wx.Font(16, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        self.cpu["font"]["14_b"] = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        self.cpu["font"]["14_n"] = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.cpu["font"]["12_b"] = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        self.cpu["font"]["12_n"] = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.cpu["font"]["10_b"] = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        self.cpu["font"]["10_n"] = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.cpu["font"]["8_b"] = wx.Font(8, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        self.cpu["font"]["8_n"] = wx.Font(8, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        self.cpu["font"]["6_b"] = wx.Font(6, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        self.cpu["font"]["6_n"] = wx.Font(6, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)

        # Set the icon of the frame
        self.icon = wx.Icon('img/icon/favicon2.ico',wx.BITMAP_TYPE_ICO)
        self.SetIcon(self.icon)
        # Set the minIcon of the taskBarIcon
        #self.taskBarIcon = TaskBarIcon(self)
        #self.Bind(wx.EVT_ICONIZE, self.OnIconfiy)                                                                       #最小化事件绑定
        #self.Bind(wx.EVT_CLOSE, self.OnExit)
        # Set the windon on screen center
        self.CenterOnScreen()

        self.__CreateMenu()
        self.__CreateToolBar()
        self.__DoLayout()
        self.__CreateLogPanel()
        #self.__InitMenuPanel()
        self.__InitToolPanel()

        # 线程管理
        #lib.thread_netstat_create(self.cpu)
        #lib.thread_heartbeat_create()

    #创建菜单栏
    def __CreateMenu(self):                                                                                             #创建菜单栏函数
        ID_Log = 11
        ID_Result = 12
        ID_Exit = 13
        ID_EN = 21
        ID_CH = 22
        ID_About = 31

        self.menuBar = wx.MenuBar()                                                                                     #创建菜单栏
        self.fileMenu = wx.Menu()                                                                                       #创建菜单
        self.fileMenu.Append(ID_Log,u"Log输出目录")                                                                     #向菜单中添加子菜单
        #self.fileMenu.Append(ID_Result, u"测试报表输出")                                                                #向菜单中添加子菜单
        self.fileMenu.Append(ID_Exit, u"退出(X)")                                                                       #向菜单中添加子菜单

        self.optionMenu = wx.Menu()                                                                                     #创建菜单
        self.optionMenu.Append(ID_EN,u"英文","Set the language into English",wx.ITEM_RADIO)                             #向菜单中添加子菜单
        self.optionMenu.Append(ID_CH,u"中文",u"将语言设置成中文",wx.ITEM_RADIO)                                          #向菜单中添加子菜单

        self.helpMenu = wx.Menu()                                                                                       #创建菜单
        self.helpMenu.Append(ID_About,u"关于...")                                                                       #向菜单中添加子菜单

        self.menuBar.Append(self.fileMenu, u"文件(F)")                                                                  #将fileMenu父菜单添加到菜单栏中
        self.menuBar.Append(self.optionMenu, u"选项(O)")                                                                #将optionMenu父菜单添加到菜单栏中
        self.menuBar.Append(self.helpMenu, u"帮组(H)")                                                                  #将helpMenu父菜单添加到菜单栏中

        self.SetMenuBar(self.menuBar)                                                                                   #将菜单栏绑定到窗体

        wx.EVT_MENU(self, ID_Log, self.OnChooseLogPath)
        #wx.EVT_MENU(self, ID_Result, self.OnOutputReport)
        wx.EVT_MENU(self, ID_Exit, self.OnExit)                                                                         #菜单事件的房顶

        wx.EVT_MENU(self, ID_EN, self.OnSetLangEN)
        wx.EVT_MENU(self, ID_CH, self.OnSetLangCH)

        wx.EVT_MENU(self, ID_About, self.OnHelp)

        # 菜单事件说明
        # EVT_MENU                   选择菜单时触发事件
        # EVT_MENU_CLOSE             关闭菜单时触发事件
        # EVT_MENU_HIGHLIGHT         菜单高亮显示时触发事件
        # EVT_MENU_HIGHLIGHT_ALL    任何菜单高亮显示时都执行同一个操作
        # EVT_MENU_OPEN              打开菜单时触发的事件

    #初始化菜单面板
    def __InitMenuPanel(self):
        self.LoadMenuTree("treeList_androidScreen")
        self.init_menu = True

    #初始化内容面板
    def __InitContentPanel(self):
        self.pager = Pager_default(self.contentPanel, self.cpu)
        self.init_page = True

    #初始化工具面板
    def __InitToolPanel(self):
        self.pager = panel_serviceSwitch(self.toolPanel, self.cpu, u"RTP语音服务切换工具")
        self.init_tool = True

    #创建工具栏
    def __CreateToolBar(self):                                                                                          #创建工具栏函数
        ID_serviceSwitch = 10001
        ID_groupAccountAdd = 10002
        ID_singleGroupUserOnline = 10003
        ID_terminalOnline = 10004
        ID_voicePressure = 10005
        ID_interComPressure = 10006
        ID_interComUpDown = 10007

        self.toolbar = self.CreateToolBar(style=wx.TB_TEXT|wx.TB_3DBUTTONS)
        self.toolbar.SetBackgroundColour(wx.Colour(240,240,240))

        # Load toolbar icons (150*50)
        icon_serviceSwitch = wx.Bitmap(os.path.join(bitmapDir, "icon_serviceSwitch.png"), wx.BITMAP_TYPE_PNG)
        icon_groupAccountAdd = wx.Bitmap(os.path.join(bitmapDir, "icon_companyAccountAdd.png"), wx.BITMAP_TYPE_PNG)
        icon_singleGroupUserOnline = wx.Bitmap(os.path.join(bitmapDir, "icon_singleGroupUserOnline.png"), wx.BITMAP_TYPE_PNG)
        icon_terminalOnline = wx.Bitmap(os.path.join(bitmapDir, "icon_terminalOnline.png"), wx.BITMAP_TYPE_PNG)
        icon_voicePressure = wx.Bitmap(os.path.join(bitmapDir, "icon_voicePressure.png"), wx.BITMAP_TYPE_PNG)
        icon_interComPressure = wx.Bitmap(os.path.join(bitmapDir, "icon_interComPressure.png"), wx.BITMAP_TYPE_PNG)
        icon_interComUpDown = wx.Bitmap(os.path.join(bitmapDir, "icon_interComUpDown.png"), wx.BITMAP_TYPE_PNG)

        self.toolbar.AddSimpleTool(ID_serviceSwitch, icon_serviceSwitch, u"RTP服务切换工具")
        self.toolbar.AddSimpleTool(ID_groupAccountAdd, icon_groupAccountAdd, u"企业用户创建工具")
        self.toolbar.AddSimpleTool(ID_singleGroupUserOnline, icon_singleGroupUserOnline, u"单组用户在线工具")
        self.toolbar.AddSimpleTool(ID_terminalOnline, icon_terminalOnline, u"账号同时在线工具")
        self.toolbar.AddSimpleTool(ID_voicePressure, icon_voicePressure, u"语音模块压测工具")
        self.toolbar.AddSimpleTool(ID_interComPressure, icon_interComPressure, u"对讲服务压测工具")
        self.toolbar.AddSimpleTool(ID_interComUpDown, icon_interComUpDown, u"对讲机上下线工具")
        #self.toolbar.AddSeparator()

        wx.EVT_TOOL(self, ID_serviceSwitch, self.OnToolBar_switchService_Click)
        wx.EVT_TOOL(self, ID_groupAccountAdd, self.OnToolBar_groupAccountAdd)
        wx.EVT_TOOL(self, ID_singleGroupUserOnline, self.OnToolBar_singleGroupUserOnline)
        wx.EVT_TOOL(self, ID_terminalOnline, self.OnToolBar_terminalOnline)
        wx.EVT_TOOL(self, ID_voicePressure, self.OnToolBar_voicePressure)
        wx.EVT_TOOL(self, ID_interComPressure, self.OnToolBar_interComPressure)
        wx.EVT_TOOL(self, ID_interComUpDown, self.OnToolBar_interComUpDown)
        self.toolbar.Realize()

    #创建Log面板
    def __CreateLogPanel(self):
        # 第二种优化方式，在TextCtrl上加一个label行
        self.logPanel_staticText = wx.StaticText(self.logPanel, -1, " Test Log Messages", (100, 30))
        self.logPanel_staticText.SetForegroundColour('#ffffff')
        self.logPanel_staticText.SetBackgroundColour('#777777')
        self.logtext = wx.TextCtrl(self.logPanel, -1, "", style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH2 | wx.TE_DONTWRAP)
        log.log_textPanel = self.logtext

        logsizer = wx.BoxSizer(wx.VERTICAL)
        logsizer.Add(self.logPanel_staticText, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 0)
        logsizer.Add(self.logtext, 1, wx.EXPAND | wx.ALL, 0)
        self.logPanel.SetSizer(logsizer)

    #实现窗口布局
    def __DoLayout(self):
        # The division of left and right structure
        self.splitter = wx.SplitterWindow(self, size=(self.client_width, self.client_height), style=wx.SP_NOBORDER)  # 创建Frmae窗体的划分器
        self.toolPanel = wx.Panel(self.splitter,-1,size=(self.toolPanel_width, self.client_height),style=wx.FIXED|wx.SUNKEN_BORDER)                                # 在底部分割窗体中中创建menuPanel
        self.logPanel = wx.Panel(self.splitter, -1, size=(self.client_width - self.toolPanel_width, self.client_height), style=wx.FIXED | wx.SUNKEN_BORDER)
        self.splitter.SplitVertically(self.toolPanel,self.logPanel,self.toolPanel_width)

    #图标化事件
    def OnIconfiy(self,event):
        self.Hide()
        event.Skip()

    #退出事件的重定义
    def OnExit(self,event):
        #self.taskBarIcon.Destroy()
        self.Destroy()
        #销毁后台进程
        self.selfDestructive = threading.Thread(target=lib.selfDestructive, args=())
        self.selfDestructive.start()

    #定义Log输入按钮的事件
    def OnChooseLogPath(self,event):
        wildcard = "Text file (*.txt)|*.txt|" \
                   "All files (*.*)|*.*"
        dlg = wx.FileDialog(self,message=u"选择Log输出文件",defaultDir=os.getcwd(),defaultFile="",wildcard=wildcard,style=wx.OPEN|wx.MULTIPLE|wx.CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            log.info('Set the Log Path: %s\n' % dlg.GetPath().encode('utf-8'))
        dlg.Destroy()

    #定义输出报表的事件
    def OnOutputReport(self,event):
        lib.outputReport(self.cpu["data"].reportSummary, self.cpu["data"].reportDetails)

    #定义选择英文按钮的事件
    def OnSetLangEN(self,event):
        log.info("Set the language into English")

    #定义选择中文按钮的事件
    def OnSetLangCH(self,event):
        log.info("Set the language into Chinese")

    #定义帮助按钮的事件
    def OnHelp(self,event):
        dlg = wx.MessageDialog(self, u"名称：杭州安正飞鸟网络科技有限公司\n"
                               u"地址：杭州市江干区九和路14号1幢326室\n"
                               u"电话：0571-87245751\n"
                               u"网址：http://www.angelcomm.cn",
                               u"关于...",wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    #工具栏事件定义——RTP服务切换工具
    def OnToolBar_switchService_Click(self,event):
        self.LoadPyTool("tool_switchService")

    #工具栏事件定义——企业用户创建工具
    def OnToolBar_groupAccountAdd(self,event):
        self.LoadPyTool("tool_groupAccountAdd")

    #工具栏事件定义——单组用户在线工具
    def OnToolBar_singleGroupUserOnline(self,event):
        self.LoadPyTool("tool_singleGroupUserOnline")

    #工具栏事件定义——企业用户在线工具
    def OnToolBar_terminalOnline(self,event):
        self.LoadPyTool("tool_terminalOnline")

    #工具栏事件定义——语音模块压测工具
    def OnToolBar_voicePressure(self,event):
        self.LoadPyTool("tool_voicePressure")

    #工具栏事件定义——语音模块压测工具
    def OnToolBar_interComPressure(self,event):
        self.LoadPyTool("tool_interComPressure")

    #工具栏事件定义——对讲机上下线工具
    def OnToolBar_interComUpDown(self,event):
        self.LoadPyTool("tool_interComUpDown")

    #加载工具页面
    def LoadPyTool(self,pyToolName):
        if self.pyToolName == pyToolName:
            return

        if self.init_tool:
            self.pager.Destroy()
            self.logtext.SetValue("")

        #工具界面加载代码
        log.TestLog("Loading the pyToolName: " + pyToolName)
        if pyToolName == "tool_switchService":
            self.pager = panel_serviceSwitch(self.toolPanel, self.cpu, u"RTP语音服务切换工具")
            log.TestLog("Start to load the switchServiceTool...")
        elif pyToolName == "tool_groupAccountAdd":
            self.pager = Pager_groupAccountAdd(self.toolPanel, self.cpu)
            log.TestLog("Start to load the groupAccountAdd...")
        elif pyToolName == "tool_singleGroupUserOnline":
            self.pager = panel_singleGroupUserOnline(self.toolPanel, self.cpu, u"单组用户在线工具")
            log.TestLog("Start to load the singleGroupUserOnline...")
        elif pyToolName == "tool_terminalOnline":
            self.pager = panel_terminalOnline(self.toolPanel, self.cpu, u"企业用户在线工具")
            log.TestLog("Start to load the terminalOnline...")
        elif pyToolName == "tool_voicePressure":
            self.pager = pager_voicePressure(self.toolPanel, self.cpu)
            log.TestLog("Start to load the voicePressure...")
        elif pyToolName == "tool_interComPressure":
            self.pager = panel_interComPressure(self.toolPanel, self.cpu, u"对讲服务压测工具")
        elif pyToolName == "tool_interComUpDown":
            self.pager = pager_interComUpDown(self.toolPanel, self.cpu)
        else:
            pass

        self.pyToolName = pyToolName

        if self.init_page:
            self.Layout()
            self.Thaw()

if __name__ == "__main__":
    app = wx.App()
    screenWH = wx.DisplaySize()
    frame = wxClient(screenWH[0],screenWH[1])
    #frame.ShowFullScreen(True, wx.FULLSCREEN_NOBORDER)
    frame.Show()
    app.MainLoop()